﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using com.huawei.esdk.tp.professional.local;
using eSDK_TP_Demo_CS_CSharp.FunctionPage;

namespace eSDK_TP_Demo_CS_CSharp
{
    /// <summary>
    /// 实现Login、Logout和KeepAlive接口
    /// </summary>
    public class AuthorizeService
    {
        private AuthorizeServiceEx service = null;
        Thread thread;
        delegate void KeepAliveResult(int result);
        private System.Timers.Timer timer = null;
        private double aliveTime = 0;

        public AuthorizeService()
        {
            service = AuthorizeServiceEx.Instance();
        }

        /// <summary>
        /// 登录认证
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>返回‘0’登录成功；其他为错误码</returns>
        public void Login()
        {
            int result = service.Login("user1", "Huawei@123");
        }

        /// <summary>
        /// 保持会话
        /// </summary>
        /// <param name="rate">心跳时间（秒）</param>
        public void KeepAlive()
        {
            int rate = 30;
            aliveTime = rate * 1000;
            thread = new Thread(new ThreadStart(KeepAliveThread));
            thread.Start();
        }

        //启动线程；使用计时器来完成心跳
        private void KeepAliveThread()
        {
            timer = new System.Timers.Timer();
            timer.Interval = aliveTime;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(AliveCode);
            timer.AutoReset = true;
            timer.Enabled = true;
        }

        //调用AuthorizeServiceEx中的KeepAlive接口实现会话处于存活状态
        private void AliveCode(object source, System.Timers.ElapsedEventArgs e)
        {
            int result = service.KeepAlive();
            Console.WriteLine(result.ToString());
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <returns>返回‘0’退出成功；其他结果为失败的错误码</returns>
        public void Logout()
        {
            int result = service.Logout();
        }
    }
}
